<template>
  <div ref="wrapRef" :class="getWrapperClass">
    <BasicForm @register="registerForm"></BasicForm>
    <TableHeader v-if="getBindValues['title']" v-bind="{ title, showTableSetting, titleHelpMessage, tableSetting }"
      @columnsChange="handlers['onColumnsChange']">
      <template #toolbar>
        <slot name="toolbar"></slot>
      </template>
    </TableHeader>
    <el-table v-bind="getBindValues" v-on="getOnValues" v-loading="getLoading" :element-loading-svg="loadingSvg"
      class="custom-loading-svg" element-loading-svg-view-box="-10, -10, 950, 950" element-loading-text="数据加载中...">
      <el-table-column type="selection" v-if="getBindValues['rowSelection']" />
      <template v-for="column in getViewColumns">
        <el-table-column v-bind="column" v-if="getBindValues['showIndexColumn'] && column['type'] === 'index'" />
        <el-table-column v-bind="column" v-else>
          <template #default="scope" v-if="column['slots']">
            <slot :name="column['slots']['customRender']" :record="scope.row">
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination class="mt-4" v-bind="getPaginationInfo" :class="getPaginationInfo['customClass']"
      @update:page-size="handleSizeChange" @update:current-page="handleCurrentChange" v-if="getShowPagination">
    </el-pagination>
  </div>
</template>
<script setup lang="ts">
import { computed, ref, toRaw, unref, useAttrs } from 'vue'
import { useDataSource } from './hooks/useDataSource'
import {
  BasicTableProps,
  ColumnChangeParam,
  InnerHandlers,
  TableActionType
} from './types/table'
import { basicProps } from './props'
import { Recordable } from '/#/global'
import { BasicForm, FormActionType } from '@/components/Form'
import { useForm } from '@/components/Form/src/hooks/useForm'
import { useLoading } from './hooks/useLoading'
import { useTableScrollTo } from './hooks/useScrollTo'
import { useColumns } from './hooks/useColumns'
import { usePagination } from './hooks/usePagination'
import { useDesign } from '@/hooks/web/useDesign'
import loadingSvg from './loadingSvg'
import { createTableContext } from './hooks/useTableContext'

import { TableHeader } from '../index'
import { useRowSelection } from './hooks/useRowSelection'
import { useCustomRow } from './hooks/useCustomRow'



const props = defineProps(
  // @ts-ignore
  basicProps
)
const emit = defineEmits<{
  (e: 'register', instance: TableActionType, formInstance: FormActionType): void
  (e: 'fetch-error'): void
  (e: 'fetch-success', data: Recordable): void
  (e: 'fetch-error'): any
  (e: 'columns-change', data: ColumnChangeParam[]): void,
  (e: 'row-click', row: Recordable, column: Recordable, event: Event): void,
  (e: 'row-contextmenu', row: Recordable, column: Recordable, event: Event): void,
  (e: 'row-dbClick', row: Recordable, column: Recordable, event: Event): void,
  (e: 'row-mouseenter', row: Recordable, column: Recordable, cell: Recordable, event: Event): void
  (e: 'row-mouseleave', row: Recordable, column: Recordable, cell: Recordable, event: Event): void

}>()

const { prefixCls } = useDesign('basic-table')

const attrs = useAttrs()
const tableElRef = ref(null)
const wrapRef = ref(null)
const tableData = ref<Recordable[]>([])
const innerPropsRef = ref<Partial<BasicTableProps>>()

function setProps(props: Partial<BasicTableProps>) {
  innerPropsRef.value = { ...unref(innerPropsRef), ...props }
}

const getProps = computed(() => {
  return { ...props, ...unref(innerPropsRef) } as BasicTableProps
})


const { getPaginationInfo, getPagination, setPagination, setShowPagination, getShowPagination } = usePagination(getProps)
console.log(getPaginationInfo.value)

const { getLoading, setLoading } = useLoading(getProps)


const [registerForm, formActions] = useForm()

const {
  handleTableChange: onTableChange,
  getDataSourceRef, // 表格数据源
  getDataSource,
  getRawDataSource,
  setTableData,
  updateTableDataRecord,
  deleteTableDataRecord,
  insertTableDataRecord,
  findTableDataRecord,
  fetch,
  getRowKey,
  reload,
  getAutoCreateKey,
  updateTableData
} = useDataSource(
  getProps,
  {
    tableData,
    getPaginationInfo,
    setLoading,
    setPagination,
    getFieldsValue: formActions.getFieldsValue
    // clearSelectedRowKeys,
  },
  emit
)

const { scrollTo } = useTableScrollTo(tableElRef, getDataSourceRef)



// row选择
const {
  getRowSelection,
  getRowSelectionRef,
  getSelectRowKeys,
  setSelectedRowKeys,
  clearSelectedRowKeys
} = useRowSelection(getProps, tableData, emit);

//自定义row事件
const { customRow } = useCustomRow(getProps, {
  setSelectedRowKeys,
  getSelectRowKeys,
  clearSelectedRowKeys,
  getAutoCreateKey,
  emit,
});

// 列配置
const { getViewColumns, getColumns, setColumns, getCacheColumns } = useColumns(getProps, getPaginationInfo)



const tableAction: TableActionType = {
  reload,
  // getSelectRows,
  // clearSelectedRowKeys,
  // getSelectRowKeys,
  // deleteSelectRowByKey,
  setPagination,
  // setTableData,
  updateTableDataRecord,
  deleteTableDataRecord,
  // insertTableDataRecord,
  // findTableDataRecord,
  // redoHeight,
  // setSelectedRowKeys,
  getRowSelection,
  setColumns,
  setLoading,
  getDataSource,
  // getRawDataSource,
  setProps,
  getPaginationRef: getPagination,
  getColumns,
  getCacheColumns,
  emit,
  // updateTableData,
  // setShowPagination,
  // getShowPagination,
  // setCacheColumnsByField,
  // expandAll,
  // expandRows,
  // collapseAll,
  scrollTo
  // getSize: () => {
  //   return unref(getBindValues).size as SizeType;
  // },
}


const handlers: InnerHandlers = {
  onColumnsChange: (data: ColumnChangeParam[]) => {
    emit('columns-change', data)
    // support useTable
    unref(getProps).onColumnsChange?.(data)
  }
}

// 绑定表格事件
const getOnValues = computed(() => {
  let on: Recordable = {
    ...customRow()
  }
  return on
})

// 绑定表格属性数据
const getBindValues = computed(() => {
  const data = unref(getDataSourceRef)
  let propsData: Recordable = {
    ...attrs,
    ...unref(getProps),
    rowSelection: unref(getRowSelectionRef),
    // scroll: unref(getScrollRef),
    pagination: toRaw(unref(getPaginationInfo)),
    loading: unref(getLoading),
    tableLayout: 'fixed',
    rowKey: unref(getRowKey),
    columns: toRaw(unref(getViewColumns)),
    data
    // ...unref(getExpandOption),
  }
  // if (slots.expandedRowRender) {
  //   propsData = omit(propsData, 'scroll');
  // }

  // propsData = omit(propsData, ['class', 'onChange']);

  return propsData
})


const getWrapperClass = computed(() => {
  const values = unref(getBindValues)
  return [
    prefixCls,
    attrs.class,
    {
      [`${prefixCls} -form - container`]: values.useSearchForm,
      [`${prefixCls} --inset`]: values.inset
    }
  ]
})

createTableContext({ ...tableAction, wrapRef, getBindValues })


emit('register', tableAction, formActions)

// 注册表格以后才能获取
const { title, showTableSetting, titleHelpMessage, tableSetting } = unref(
  getProps
)


const handleCurrentChange = async (val: number) => {
  setPagination({
    currentPage: val
  })
  await reload()
}
const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  setPagination({
    pageSize: val
  })
  await reload()


}


</script>
<style lang="scss">
</style>
